<?php
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends Controller{
	
	public function index(){
		//分配模型缓存数据
		$value=S('m');
		$this->assign('data',$value);
		//模板目录
		$template=C('template_style');
		// $style =  \Org\Util\Dir::tree("Template/$template",'html');
		$style=glob("./Template/$template/*.html");
		$menu=array();
		foreach ($style as $k => $v) {
			$menu[]=basename($v);
		}
		//栏目列表
		$categoryData=S('c');
		$data=$this->find_son($categoryData,0);
		//样式显示
		// p($data);exit;
		$this->assign('cate',$data);
		$this->assign('tpl',$menu);
		$this->display();
	}	
	//添加栏目
	public function add(){
		// p($_POST);exit;
		if(IS_POST){
			$Model=D('Category');
			if($Model->d()){
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}else{
			$this->error('没有POST');
		}
		
	}
	//编辑
	public function edit(){
		$Model=D('Category');
		if(IS_AJAX){
			$data=$Model->edit();
			// dump($data);exit;
			
			$value=S('c');
			$cate=array();
			foreach ($value as $k => $v) {
				if($v['pid']==0){
					$cate[]=$v;
				} 
			}
			$model=S('m');
			
			//模板文件
			$template=C('template_style');
			// $style =  \Org\Util\Dir::tree("Template/$template",'html');
			$style=glob("./Template/$template/*.html");
			$tpl=array();
			foreach ($style as $k => $v) {
				$tpl[]=basename($v);
			}
			$this->assign('tpl',$tpl);
			$this->assign('data',$data);
			$this->assign('cate',$cate);
			$this->assign('md',$model);
			$this->display();
		}else{

			if($Model->alter()){
				$this->success('修改成功');
			}else{
				$this->error('修改失败');
			}
		}


	}
	
	//删除
	public function del(){
		$Model=D('Category');
		if($Model->dorp()){
			echo 1;exit;
		}else{
			echo 0;exit;
		}
	}

	//更新缓存
	public function updateCache(){
		$Model=D('Category');
		if($Model->updateCache()){
			echo 1;
		}else{
			echo 0;
		}
	}




	//查找子孙栏目
	public function find_son($arr,$id,$level=0){
		static $array=array();
		foreach($arr as $v){
			if($v['pid']==$id){
			$v['level']=$level+2;
			$array[]=$v;
			//到临界条件
			$this->find_son($arr,$v['cid'],$v['level']);
			}
		}
		return $array;
	}


}